package com.fs.ibox_h.web;

import com.alibaba.fastjson.JSON;
import com.fs.ibox_h.pojo.User;
import com.fs.ibox_h.servie.UserService;
import com.fs.ibox_h.util.BeanFactory;
import com.fs.ibox_h.util.DateUtil;
import com.fs.ibox_h.util.ResponseDataUtil;
import com.fs.ibox_h.util.ResponseJSONUtil;
import com.fs.ibox_h.vo.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

@WebServlet(name = "UserServlet",value = "/user/*")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String path = request.getPathInfo();
        String[] paths = path.replaceFirst("/", "").split("/");


        if ("selectByCondition".equalsIgnoreCase(paths[0])) {
            // 根据条件查询
            selectByConditionAndUser(request, response);
        }

    }

    private void selectByConditionAndUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String cstate = request.getParameter("cstate");

        UserCondition userCondition = new UserCondition();
        userCondition.setUsername(username);

        if (cstate != null && !cstate.isEmpty()){
            userCondition.setCstate(Integer.parseInt(cstate));
        }


        String currentPage = request.getParameter("currentPage");
        String pageSize = request.getParameter("pageSize");
        System.out.println();
        Date date3 = null;

        int currentPageInt = 1;
        int pageSizeInt = 3;

        if (currentPage!=null && !currentPage.isEmpty() ){
            currentPageInt = Integer.parseInt(currentPage);
        }

        if (pageSize!=null && !pageSize.isEmpty()){
            pageSizeInt = Integer.parseInt(pageSize);
        }

        UserService service = BeanFactory.createBean(UserService.class);
        Page<User> userPage = service.selceByCondition(currentPageInt, pageSizeInt, userCondition);
        ResponseData responseData = ResponseDataUtil.buildOk(userPage);
        ResponseJSONUtil.responseJSON(responseData,response);


    }

    private String tonull(String str) {
        if (str.isEmpty() || str == null) {
            str = null;
        }
        return str;
    }
}
